<template>
  <el-card>
    <el-input size="small" disabled :value="$route.query.roleName"></el-input>
    <el-tree
      ref="treeRef"
      :data="roleList"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      class="mt-20"
      default-expand-all
      @check="checked"
    >
    </el-tree>
    <el-button type="primary" size="small" @click="saveHandler" >保存</el-button>
    <el-button class="mt-20" size="small" @click="cancel" >取消</el-button>
  </el-card>
</template>

<script>
import roleApi from "@/api/role";
import { Message } from 'element-ui';
export default {
  name: "Auth",
  data() {
    return {
      roleList: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      checkedList: [],
      roleId: '',
      permissionId: ''
    };
  },
  methods: {
    async getRoleList() {
      try {
        let result = await roleApi.toAssign(this.roleId);
        this.roleList = result.children;
      } catch (error) {
        console.error(error);
      }
    },
    // 过滤选择的按钮级别权限
    filterSelectRole(list) {
      list.filter(item => {
        if(item.children.length != 0) {
          this.filterSelectRole(item.children)
        }
        return item.type == 2 && item.select
      })
      .forEach(item => {
        this.checkedList.push(item.id)
      })
      this.$refs.treeRef.setCheckedKeys(this.checkedList)
    },
    checked(checkedNodes, checkedKeys) {
      this.permissionId = checkedKeys.checkedKeys.concat(checkedKeys.halfCheckedKeys).join() 
    },
    async saveHandler() {
      try {
        await  roleApi.doAssign(this.roleId, this.permissionId)
        this.$router.back()
        Message.success('分配权限成功')
      } catch (error) {
        console.error(error)
        Message.error('分配权限失败')
      }
    },
    cancel() {
      this.$router.back();
    }
  },
  async mounted() {
    this.roleId = this.$route.query.id;
    await this.getRoleList();
    this.filterSelectRole(this.roleList);
  },
};
</script>

<style>
</style>